//
//  ProductTableView.m
//  tableView联动
//
//  Created by 程建良 on 16/8/20.
//  Copyright © 2016年 程建良. All rights reserved.
//

#import "ProductTableView.h"
//indexPath的位置
#define INDEXPATHORIGIN(TABVIEW,A,B) [TABVIEW rectForRowAtIndexPath:[NSIndexPath indexPathForRow:A inSection:B]].origin
@interface ProductTableView()<UITableViewDataSource,UITableViewDelegate>

@end
@implementation ProductTableView

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.delegate = self;
        self.dataSource = self;
        [self registerClass:[UITableViewCell class] forCellReuseIdentifier:@"product"];
        //接受通知
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(sectionChange:) name:@"sectionChange" object:nil];
        self.showsVerticalScrollIndicator = NO;
    }
    return self;
}
-(void)setArray:(NSArray<NSArray *> *)array{
    _array = array;
    [self reloadData];
}
#pragma mark --通知实现--
-(void)sectionChange:(NSNotification*)notification{
    NSString * index = notification.object;
    [self selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index.integerValue] animated:YES scrollPosition:UITableViewScrollPositionTop];
    [self setContentOffset:INDEXPATHORIGIN(self, 0, index.integerValue) animated:YES];
}
#pragma mark -- UItableViewDataSource --
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.array.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.array[section].count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"product"];
    cell.textLabel.text = [NSString stringWithFormat:@"%@",self.array[indexPath.section][indexPath.row]];
    return cell;
}
#pragma mark -- UITableViewDelegate --
//实现product至tap联动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if ( scrollView.contentOffset.y <= INDEXPATHORIGIN(self, self.array[0].count-1, 0).y+100 ) {
        //发送通知
        [[NSNotificationCenter defaultCenter]postNotificationName:@"offsetChange" object:@(0)];  }
    for (int i = 1; i < self.array.count ; i++) {
        if (scrollView.contentOffset.y> INDEXPATHORIGIN(self, self.array[i-1].count-1, i-1).y+100 && scrollView.contentOffset.y <= INDEXPATHORIGIN(self, self.array[i].count-1, i).y+100 ){
            //发送通知
            [[NSNotificationCenter defaultCenter]postNotificationName:@"offsetChange" object:@(i)];
        }
    }
}
//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
#pragma mark --移除监听--
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
